package com.exam.controller;


import com.baidu.aip.face.AipFace;
import com.baidu.aip.util.Base64Util;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import java.util.Base64;


@Controller
@RequestMapping("/face")
public class FaceLoginController {

    //人脸登录
    @RequestMapping("/toFace")
    public String toFace(){
        return "getface.html";
    }

    @ResponseBody

    @RequestMapping("/face-login")
    public  String searchface(@RequestBody @RequestParam(name = "imagebast64") String imagebast64, HttpServletRequest request) throws Exception {

        AipFace client = new AipFace("","","");//这里需要自己申请一个百度账号，注册一下，人脸识别是可以免费使用的，申请完之后填入你的相关参数即可。
        String image = imagebast64.replace("data:image/png;base64,", "");//image/png;base64,更换为空得到真正的图片数据
        byte[] imageDataBytes = Base64.getDecoder().decode(image);
        String imagee = Base64Util.encode(imageDataBytes);//将二进制转换为base64
        JSONObject res = client.search(imagee,"BASE64","face",null);
        System.out.println(res.toString(2));
        Object error_code = res.get("error_code");
        Integer result = (Integer)error_code;
        if (result == 0){
            return "恭喜你认证成功";
        }
        return "认证失败请重新刷脸登录";
    }
    @RequestMapping("/success")
    public RedirectView redirect() {
        RedirectView redirectView = new RedirectView();
        redirectView.setUrl("http://localhost:8088/#/");
        return redirectView;//请求重定向
    }
    @RequestMapping("/error")
    public RedirectView error() {
        RedirectView redirectView = new RedirectView();
        redirectView.setUrl("http://localhost:8080/");
        return redirectView;//请求重定向
    }
}